package com.hwy.catering.interceptor;

import com.hwy.catering.annotation.AccessLimit;
import com.hwy.catering.utils.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 接口限流拦截器
 */
public class AccessLimitInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public AccessLimitInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //没有加@AccessLimit注解就放行
            if (!method.isAnnotationPresent(AccessLimit.class)) {
                return true;
            }
            AccessLimit accessLimit = method.getAnnotation(AccessLimit.class);
            //注解里面的条件为空，放行
            if (accessLimit == null) {
                return true;
            }
            int limit = accessLimit.limit();
            int sec = accessLimit.sec();
            String ipAddress = request.getHeader("x-forwarded-for");
            String key = ipAddress + request.getRequestURI();
            String maxLimit = stringRedisTemplate.opsForValue().get(key);
            if (maxLimit == null) {//没有命中缓存
                stringRedisTemplate.opsForValue().set(key, "1", sec, TimeUnit.SECONDS);  //set时一定要加过期时间
            } else if (Integer.valueOf(maxLimit) < limit) { //没到限流最大值
                stringRedisTemplate.opsForValue().set(key, String.valueOf(maxLimit + 1), sec, TimeUnit.SECONDS);
            } else {
//                output(response, "请求太频繁。");
                response.setStatus(429);
                System.out.println("用户请求过于频繁。");
                return false;
            }
        }
        return true;
    }

    public void output(HttpServletResponse response, String msg) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            outputStream.write(msg.getBytes("UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            outputStream.flush();
            outputStream.close();
        }
    }
}
